package group2.beans;

import group2.core.UserLevel;
import group2.core.database.IJpaCtrl;
import group2.core.database.JpaCtrlFactory;
import group2.core.database.NonexistentEntityException;
import group2.core.entities.CamelUser;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;

/**
 * Used for managing the users and other administrative stuff.
 * 
 * @author cnilsson
 */
@ManagedBean
@ViewScoped
public class AdminControllerBean implements Serializable{

    private List<CamelUser> users;
    private IJpaCtrl<CamelUser> ctrl;
    
    private void populateUsers(){
        users = ctrl.findEntities();
    }

    public void deleteUser(ActionEvent e){
          CamelUser u  = (CamelUser)e.getComponent().getAttributes().get("user");
        try{ctrl.destroy(u.getId());
        }
        catch(NonexistentEntityException nee){
            
        }
    }    
    
    public void setUser(ActionEvent e){
        CamelUser u  = (CamelUser)e.getComponent().getAttributes().get("user");
       u.setUserLevel(UserLevel.USER); 
        try{ctrl.edit(u);
        
        }
       catch(Exception ee){
            
        }
    }
     public void setWriter(ActionEvent e){
        CamelUser u  = (CamelUser)e.getComponent().getAttributes().get("user");
       u.setUserLevel(UserLevel.WRITER); 
        try{ctrl.edit(u);
        
        }
       catch(Exception ee){
            
        }
    }
     
      public void setAdmin(ActionEvent e){
        CamelUser u  = (CamelUser)e.getComponent().getAttributes().get("user");
       u.setUserLevel(UserLevel.ADMIN); 
        try{ctrl.edit(u);
        
        }
       catch(Exception ee){
            
        }
    }
    
    public List<CamelUser> getUsers() {
        return users;
    }

    public void setUsers(List<CamelUser> users) {
        this.users = users;
    }
    
    /** Creates a new instance of AdminControllerBean */
    public AdminControllerBean() {
        ctrl = JpaCtrlFactory.getInstance().getCamelUserCtrl();
        populateUsers();
    }
}
